package com.movie.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.movie.entity.User;
import com.movie.mapper.UserMapper;
import com.movie.service.SmsService;
import com.movie.vo.Result;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import utils.JwtUtils;
import utils.RsaUtils;
import utils.VerifyCodeUtil;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.PrivateKey;
import java.util.concurrent.TimeUnit;

@Service
public class ISmsService implements SmsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public static final String url = "http://gw.api.taobao.com/router/rest";
    public static final	String appkey = "23473071";
    public static final	String secret = "951efdcc9540d2c0c1646ed6d74892e6";



    @Override
    public Result sendMsg(String phone) {
        if(StringUtils.isEmpty(phone))
            return new Result(false,"非法参数");
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("phone",phone);

        User existUser = userMapper.selectOne(queryWrapper);

        if(StringUtils.isEmpty(existUser))
            return new Result(false,"登录失败");
//        获取验证码
        String code = VerifyCodeUtil.generateVerifyCode(6, "0123456789");
        TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
        AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
        req.setExtend("123456");
        req.setSmsType("normal");
        req.setSmsFreeSignName("问道学院");
        req.setSmsParamString("{\"code\":\""+code+"\"}");
        req.setRecNum(phone);
        req.setSmsTemplateCode("SMS_209190607");
        AlibabaAliqinFcSmsNumSendResponse rsp = null;
        try {
            rsp = client.execute(req);
        } catch (ApiException e) {
            e.printStackTrace();
        }
//        System.out.println(rsp.getBody());
        Boolean success = rsp.getResult().getSuccess();
        if (success) {
            //将验证码存放到redis中
            stringRedisTemplate.boundValueOps("sms:"+phone).set(code);
            //设置过期时间(60s)
            stringRedisTemplate.expire("sms:"+phone,7, TimeUnit.DAYS);
            return new Result(true,"发送成功");
        }else{
            return new Result(false,"短信发送失败，请稍后重试");
        }

    }

    @Override
    public Result verifyCode(String phone, String code) {
        //根据phone从redis中获取code
        String redisCode = stringRedisTemplate.boundValueOps("sms:" + phone).get();

        if (redisCode == null)
            return new Result(false,"登录失败");

        if(!redisCode.equals(code))
            return new Result(false,"登录失败");


        //清除redis中的验证码
        stringRedisTemplate.delete("sms:" + phone);

        //获取用户的信息
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("phone",phone);

        User existUser = userMapper.selectOne(queryWrapper);

        existUser.setPassword("");
        //颁发令牌
        PrivateKey privateKey = null;
        try {
            ClassPathResource resource = new ClassPathResource("rsa.pri");
            InputStream inputStream = resource.getInputStream();
            privateKey = RsaUtils.getPrivateKey(readBytes3(inputStream));
        } catch (Exception e) {
            e.printStackTrace();
        }
        String jwtToken = JwtUtils.generateTokenExpireInMinutes(existUser, privateKey, 60);


        return new Result(true,"登录成功",jwtToken);
    }
    public static byte[] readBytes3(InputStream in) throws IOException {
        BufferedInputStream bufin = new BufferedInputStream(in);
        int buffSize = 1024;
        ByteArrayOutputStream out = new ByteArrayOutputStream(buffSize);

        // System.out.println("Available bytes:" + in.available());

        byte[] temp = new byte[buffSize];
        int size = 0;
        while ((size = bufin.read(temp)) != -1) {
            out.write(temp, 0, size);
        }
        bufin.close();

        byte[] content = out.toByteArray();
        return content;
    }
}
